<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" @click="handleQuery">搜索</el-button>
        <el-button size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="small"
          @click="handleAdd"
          v-hasPermi="['system:category:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain

          size="small"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:category:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          size="small"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:category:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          size="small"
          @click="handleExport"
          v-hasPermi="['system:category:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="categoryList" @selection-change="handleSelectionChange"
              row-key="id"
              :default-expand-all="true"
              :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="{ row }">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(row)">修改</el-button>
          <el-button link type="primary" icon="Plus" @click="handleAdd(row)">新增</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改知识分类对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="form" :model="formData" :rules="rules" label-width="80px">
        <el-col :span="24">
          <el-form-item label="上级菜单">
            <el-tree-select
                v-model="formData.parentId"
                :data="treeSelectData"
                :props="{ value: 'id', label: 'name', children: 'children' }"
                value-key="id"
                placeholder="选择上级菜单"
                check-strictly
            />
          </el-form-item>
        </el-col>
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { listCategory, getCategory, delCategory, addCategory, updateCategory } from "@/api/knowledge/category";
import {listMenu} from "@/api/system/menu.js";

let { proxy } = getCurrentInstance();

const isEdit = ref(false);

// 表达你的引用
const form = ref();

// 遮罩层
const loading = ref(false);
// 选中数组
const ids = ref([]);

// 非单个禁用
const single = ref(true);

// 非多个禁用
const multiple = ref(true);


// 显示搜索条件
const showSearch = ref(true);

// 总条数
const total = ref(0);

// 知识分类表格数据
const categoryList = ref([]);

const title = computed(()=> {
  return isEdit.value ? '编辑' : '增加';
});

// 是否显示弹出层
const open = ref(false);

const treeSelectData = ref([]);


  const queryParams = reactive({
      pageNum: 1,
      pageSize: 10,
      name: null,
  });

const initFormData = {
  id: 0,
  name: null,
  parentId: 0,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  remark: null
}

// 表单参数
  const formData = reactive({ ...initFormData });

// 表单校验
const rules = {
  name: [
    { required: true, message: "名称不能为空", trigger: "blur" }
  ],
}

/** 查询知识分类列表 */
function getList() {
  loading.value = true;
  listCategory(queryParams).then(response => {

    const rows = proxy.handleTree(response.rows, "id");

    categoryList.value = rows;

    total.value = rows.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}



// 表单重置
function reset() {
  Object.assign(formData, { ...initFormData });
  proxy.resetForm("form");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryForm");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length!==1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd(row) {
  reset();
  open.value = true;
  title.value = "添加知识分类";
  getTreeSelectData();

  isEdit.value = false;

  if (row) {
    formData.parentId = row.id;
  } else {
    formData.parentId = 0;
  }

}


/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  const id = row.id || this.ids;
  await getTreeSelectData();
  getCategory(id).then(response => {
    Object.assign(formData, response.data);
    open.value = true;
    title.value = "修改知识分类";
  });
}


/** 提交按钮 */
function submitForm() {
  form.value.validate(valid => {
    if (valid) {
      if (isEdit.value) {
        updateCategory(formData).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCategory(formData).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除知识分类编号为"' + ids + '"的数据项？').then(function() {
    return delCategory(ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/category/export', {
    ...queryParams
  }, `category_${new Date().getTime()}.xlsx`)
}

function getTreeSelectData() {
  treeSelectData.value = [];
  return listCategory().then(response => {
    const treeData = { id: 0, name: "主类目", children: [] };
    treeData.children = proxy.handleTree(response.rows, "id");
    treeSelectData.value.push(treeData);
  });
}

onMounted( ()=> {
  getList();
})

</script>
